package Thread.yield;

import java.util.concurrent.TimeUnit;

public class OneToOne {
    public static String value = "";

    public static void main(String[] args) {
        Object lock = new Object();
        new Thread(new OneToOneProduce(lock)).start();
        new Thread(new OneToOneResume(lock)).start();
    }
}

class OneToOneProduce implements Runnable {
    private Object lock;

    public OneToOneProduce(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (lock) {
                if (!"".equals(OneToOne.value)) {
                    System.out.println("生产者开始等待...");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                OneToOne.value = System.currentTimeMillis() + "";
                System.out.println("生产者生产值为：" + OneToOne.value);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.notify();
            }
        }
    }
}

class OneToOneResume implements Runnable {
    private Object lock;

    public OneToOneResume(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (lock) {

                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if ("".equals(OneToOne.value)) {
                    System.out.println("消费者开始等待...");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("消费者获取值为：" + OneToOne.value);
                OneToOne.value = "";
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.notify();
            }
        }
    }
}
